package com.exmaple.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class IpUtil {

    public static final String PREF = ":";

    public static final String MARK = ";";

    public static String getIp() {
        String ip = null;
        try {
            InetAddress localAddress = null;
            Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
            while (ifaces.hasMoreElements()) {
                NetworkInterface iface = ifaces.nextElement();
                Enumeration<InetAddress> addresses = iface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (!address.isLinkLocalAddress() && !address.isLoopbackAddress() && address instanceof Inet4Address) {
                        localAddress = address;
                        break;
                    }
                }
                if (localAddress != null) {
                    break;
                }
            }
            if (localAddress != null) {
                ip = localAddress.getHostAddress();
            }
        } catch (Exception e) {
        }
        return ip;
    }
}
